/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gtracker;

import java.sql.*;

/**
 * The Database class is responsible for
 * all the interactions with the Database
 * like adding a user, checking a usernames
 * availability.
 * @author sajin
 */
public class Database {

	/**
	 * The MySQL Database connection details are
	 * passed on to this constructor.
	 * @param userName userName for the database user.
	 * @param passWord passWord for the database user.
	 * @param serverUrl URL of the database.
	 */
    public void openConnection(String userName, String passWord, String serverUrl) throws Exception {
		this.userName = userName;
		this.passWord = passWord;
		this.serverUrl = serverUrl;

		dbConnection = null;
		Class.forName("com.mysql.jdbc.Driver").newInstance();

		dbConnection = DriverManager.getConnection(serverUrl, userName, passWord);
		Statement createUserTable = dbConnection.createStatement();
		createUserTable.executeUpdate(
			"CREATE TABLE IF NOT EXISTS users(" +
			"UserName varchar(40) NOT NULL," +
			"PassWord varchar(128) NOT NULL," +
			"PublicKey varchar(128) NOT NULL," +
			"PRIMARY KEY(UserName))");

    }

	@Override
	protected void finalize() throws Throwable {
		dbConnection.close();
	}

	public void closeConnection() {
		try {
			dbConnection.close();
		} catch ( SQLException sqexp ) {
			System.err.println( sqexp.getCause() );
		}
	}

	/**
	 * Check with the database that the
	 * user name and password is correct.
	 * @return True if matching username/password.
	 *	   False otherwise.
	 */

	public boolean isAuthenticUser( String userName , String passWord ) {
		int userCount =0;

		try {
			Statement userAuth = dbConnection.createStatement();
			userAuth.execute(
				"SELECT COUNT(*) FROM users WHERE UserName='" +
				userName + "' AND PassWord='" + passWord + "'"
				);
			ResultSet resultUserAvail = userAuth.getResultSet();
			resultUserAvail.first();
			userCount = resultUserAvail.getInt(1);
			userAuth.close();
		} catch ( SQLException sqlExp ) {
			System.err.println("Error Occured " + sqlExp.getMessage() );
		}

		if ( userCount == 1 )
			return true;
		else
			return false;
	}

	protected String userName;
	protected String passWord;
	protected String serverUrl;
	protected Connection dbConnection;
}
